﻿using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace YArchitech.Controls
{
	public class Zip
	{
		public static bool ZipFile(string[] filename, string zipFilePath, out string err)
		{
			err = "";
			if (zipFilePath == string.Empty)
			{
				zipFilePath = "未命名.zip";
			}
			try
			{
				using (ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(zipFilePath)))
				{
					zipOutputStream.SetLevel(9);
					byte[] array = new byte[4096];
					foreach (string path in filename)
					{
						zipOutputStream.PutNextEntry(new ZipEntry(Path.GetFileName(path))
						{
							DateTime = DateTime.Now
						});
						using (FileStream fileStream = File.OpenRead(path))
						{
							int num;
							do
							{
								num = fileStream.Read(array, 0, array.Length);
								zipOutputStream.Write(array, 0, num);
							}
							while (num > 0);
						}
					}
					zipOutputStream.Finish();
					zipOutputStream.Close();
				}
			}
			catch (Exception ex)
			{
				err = ex.Message;
				return false;
			}
			return true;
		}

		public static bool UnZipFile(string zipFilePath, string unZipDir, out string err)
		{
			err = "";
			if (zipFilePath == string.Empty)
			{
				err = "压缩文件不能为空！";
				return false;
			}
			if (!File.Exists(zipFilePath))
			{
				err = "压缩文件不存在！";
				return false;
			}
			if (unZipDir == string.Empty)
			{
				unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
			}
			if (!unZipDir.EndsWith("//"))
			{
				unZipDir += "//";
			}
			if (!Directory.Exists(unZipDir))
			{
				Directory.CreateDirectory(unZipDir);
			}
			try
			{
				using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)))
				{
					ZipEntry nextEntry;
					while ((nextEntry = zipInputStream.GetNextEntry()) != null)
					{
						string text = Path.GetDirectoryName(nextEntry.Name);
						string fileName = Path.GetFileName(nextEntry.Name);
						if (text.Length > 0)
						{
							Directory.CreateDirectory(unZipDir + text);
						}
						if (!text.EndsWith("//"))
						{
							text += "//";
						}
						if (fileName != string.Empty)
						{
							using (FileStream fileStream = File.Create(unZipDir + nextEntry.Name))
							{
								byte[] array = new byte[2048];
								for (;;)
								{
									int num = zipInputStream.Read(array, 0, array.Length);
									if (num <= 0)
									{
										break;
									}
									fileStream.Write(array, 0, num);
								}
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				err = ex.Message;
				return false;
			}
			return true;
		}
	}
}
